<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属产品" prop="productId">
        <el-select v-model="queryParams.productId" placeholder="请选择产品" clearable>
          <el-option
            v-for="item in productOptions"
            :key="item.productId"
            :label="item.productName"
            :value="item.productId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属公寓" prop="hotelId">
        <el-select v-model="queryParams.hotelId" placeholder="请选择公寓" clearable>
          <el-option
            v-for="item in hotelOptions"
            :key="item.hotelId"
            :label="item.hotelName"
            :value="item.hotelId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="房间名" prop="roomName">
        <el-input
          v-model="queryParams.roomName"
          placeholder="请输入房间名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.device_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="电路开关" prop="circuitSwitch" v-if="showCols.circuitSwitch">
        <el-select v-model="queryParams.circuitSwitch" placeholder="请选择电路开关" clearable>
          <el-option
            v-for="dict in dict.type.device_circuit_switch"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="扫码开电" prop="scanPoweron" v-if="showCols.scanPoweron">
        <el-select v-model="queryParams.scanPoweron" placeholder="请选择扫码开电" clearable>
          <el-option
            v-for="dict in dict.type.device_scan_poweron"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="人走断电" prop="leavePoweroff" v-if="showCols.leavePoweroff">
        <el-select v-model="queryParams.leavePoweroff" placeholder="请选择人走断电" clearable>
          <el-option
            v-for="dict in dict.type.device_leave_poweroff"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['device:device:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['device:device:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['device:device:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['device:device:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange" v-if="!isMobile">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备名称/产品名称" align="center" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.deviceName }}<br>【{{ scope.row.productName }}】</span>
        </template>
      </el-table-column>
      <el-table-column label="所属公寓/房间名称" align="center" width="130">
        <template slot-scope="scope">
          <span>{{ scope.row.hotelName }}<br>【{{ scope.row.roomName }}】</span>
        </template>
      </el-table-column>
      <el-table-column label="设备状态/最后上线时间" align="center" width="180">
        <template slot-scope="scope">
          <span><dict-tag :options="dict.type.device_status" :value="scope.row.status"/>{{ parseTime(scope.row.lastOnlineTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电路开关" align="center" prop="circuitSwitch" v-if="showCols.circuitSwitch">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.device_circuit_switch" :value="scope.row.circuitSwitch"/>
        </template>
      </el-table-column>
      <el-table-column label="扫码开电" align="center" prop="scanPoweron" v-if="showCols.scanPoweron">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.scanPoweron"
            active-value="1"
            inactive-value="0"
            @change="handleScanPoweronChange(scope.row)"
          ></el-switch><br>
          <span>【断电：{{ scope.row.ddTime }}】</span>
        </template>
      </el-table-column>
      <el-table-column label="人走断电" align="center" prop="leavePoweroff" v-if="showCols.leavePoweroff">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.leavePoweroff"
            active-value="1"
            inactive-value="0"
            @change="handleLeavePoweroffChange(scope.row)"
          ></el-switch><br>
          <span>【长通：{{ scope.row.ctBeginTime }}~{{ scope.row.ctEndTime }}】</span>
        </template>
      </el-table-column>
      <el-table-column label="Wi-Fi名称/密码" align="center" width="120" v-if="showCols.wifi">
        <template slot-scope="scope">
          <span>{{ scope.row.wifiName }}<br>{{ scope.row.wifiPswd }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="210" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCircuitSwitchChange(scope.row, '11')"
            v-hasPermi="['device:device:edit']"
            v-if="showCols.circuitSwitch"
          >远程通电</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCircuitSwitchChange(scope.row, '01')"
            v-hasPermi="['device:device:edit']"
            v-if="showCols.circuitSwitch"
          >远程断电</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCircuitSwitchChange(scope.row, '02')"
            v-hasPermi="['device:device:edit']"
            v-if="showCols.circuitSwitch"
          >强制断电</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleReportDevice(scope.row)"
            v-hasPermi="['device:device:edit']"
            v-if="showCols.reportDevice"
          >上报设备</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleGetPowerQrcode(scope.row)"
            v-hasPermi="['device:device:edit']"
            v-if="showCols.scanPoweron"
          >取电二维码</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:device:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleLog(scope.row)"
            v-hasPermi="['device:device:log']"
          >设备日志</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handlePower(scope.row)"
            v-hasPermi="['device:device:power']"
          >用电记录</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['device:device:remove']"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <el-table v-loading="loading" :data="deviceList" v-if="isMobile">
      <el-table-column label="设备信息" align="left">
        <template slot-scope="scope">
          <span style="font-size: 12px">
            <b>设备名称：</b>{{ scope.row.deviceName }}<br>
            <b>产品名称：</b>{{ scope.row.productName }}<br>
            <b>所属公寓：</b>{{ scope.row.hotelName }}<br>
            <b>房间名称：</b>{{ scope.row.roomName }}<br>
            <b>设备状态：</b><dict-tag :options="dict.type.device_status" :value="scope.row.status" />
            <b>最后上线时间：</b>{{ parseTime(scope.row.lastOnlineTime, '{y}-{m}-{d} {h}:{i}:{s}') }}<br>
            <b>电路开关：</b><dict-tag :options="dict.type.device_circuit_switch" :value="scope.row.circuitSwitch"/>
            <b>扫码开电：</b>
            <el-switch
              v-model="scope.row.scanPoweron"
              active-value="1"
              inactive-value="0"
              @change="handleScanPoweronChange(scope.row)"
            ></el-switch><br>
            <b>人走断电：</b>
            <el-switch
              v-model="scope.row.leavePoweroff"
              active-value="1"
              inactive-value="0"
              @change="handleLeavePoweroffChange(scope.row)"
            ></el-switch><br>
            <b>长通时段：</b>{{ scope.row.ctBeginTime }} ~ {{ scope.row.ctEndTime }}<br>
            <b>断电时间：</b>{{ scope.row.ddTime }}<br>
            <b>Wi-Fi名称：</b>{{ scope.row.wifiName }}<br>
            <b>Wi-Fi密码：</b>{{ scope.row.wifiPswd }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="85" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCircuitSwitchChange(scope.row, '11')"
            v-hasPermi="['device:device:edit']"
            style="margin-left: 0px"
            v-if="showCols.circuitSwitch"
          >远程通电</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCircuitSwitchChange(scope.row, '01')"
            v-hasPermi="['device:device:edit']"
            style="margin-left: 0px"
          >远程断电</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCircuitSwitchChange(scope.row, '02')"
            v-hasPermi="['device:device:edit']"
            style="margin-left: 0px"
          >强制断电</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleReportDevice(scope.row)"
            v-hasPermi="['device:device:edit']"
            style="margin-left: 0px"
          >上报设备</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleGetPowerQrcode(scope.row)"
            v-hasPermi="['device:device:edit']"
            style="margin-left: 0px"
          >取电二维码</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:device:edit']"
            style="margin-left: 0px"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleLog(scope.row)"
            v-hasPermi="['device:device:log']"
            style="margin-left: 0px"
          >设备日志</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handlePower(scope.row)"
            v-hasPermi="['device:device:power']"
            style="margin-left: 0px"
          >用电记录</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['device:device:remove']"-->
<!--            style="margin-left: 0px"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="basic">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="所属产品" prop="productId" v-if="!form.deviceId">
              <el-select v-model="form.productId" placeholder="请选择产品">
                <el-option
                  v-for="item in productOptions"
                  :key="item.productId"
                  :label="item.productName"
                  :value="item.productId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属公寓" prop="hotelId" v-if="form.deviceId">
              <el-select
                v-model="form.hotelId"
                placeholder="请选择公寓"
                clearable
                style="width: 100%">
                <el-option
                  v-for="item in hotelOptions"
                  :key="item.hotelId"
                  :label="item.hotelName"
                  :value="item.hotelId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="设备名称" prop="deviceName" v-if="!form.deviceId">
              <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
            </el-form-item>
            <el-form-item label="房间名称" prop="roomName" v-if="form.deviceId">
              <el-input v-model="form.roomName" placeholder="请输入房间名称" />
            </el-form-item>
            <el-form-item label="房间地址" prop="roomAddress" v-if="form.deviceId">
              <el-input v-model="form.roomAddress" placeholder="请输入房间地址" />
            </el-form-item>
            <el-form-item label="房间户型" prop="roomLayout" v-if="form.deviceId">
              <el-select
                v-model="form.roomLayout"
                placeholder="请输入房间户型"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.device_hotel_layout"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="控电功率（千瓦）" prop="roomPowerCapacity" v-if="form.deviceId" style="width: 100%">
              <el-input v-model="form.roomPowerCapacity" placeholder="请输入控电功率" />
            </el-form-item>
            <el-form-item label="用电单价（元）" prop="roomPowerPrice" v-if="form.deviceId" style="width: 100%">
              <el-input v-model="form.roomPowerPrice" placeholder="请输入用电单价" />
            </el-form-item>
            <el-form-item label="设备数量" prop="deviceCount" v-if="!form.deviceId">
              <el-input v-model="form.deviceCount" placeholder="请输入设备数量" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="WIFI信息" name="wifiInfo" v-if="showCols.wifi">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="Wi-Fi名称" prop="wifiName" v-if="form.deviceId">
              <el-input v-model="form.wifiName" placeholder="请输入Wi-Fi名称" />
            </el-form-item>
            <el-form-item label="Wi-Fi密码" prop="wifiPswd" v-if="form.deviceId">
              <el-input v-model="form.wifiPswd" placeholder="请输入Wi-Fi密码" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="长通时段" name="ctInfo" v-if="showCols.leavePoweroff">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="长通时段(开始时间)" prop="ctBeginTime" v-if="form.deviceId" style="width: 100%">
<!--              <el-input v-model="form.ctBeginTime" placeholder="请输入开始时间(HH:mm)" />-->
              <el-time-picker
                v-model="form.ctBeginTime"
                style="width: 100%"
                format='HH:mm'
                value-format="HH:mm"
                :editable="false">
              </el-time-picker>
            </el-form-item>
            <el-form-item label="长通时段(结束时间)" prop="ctEndTime" v-if="form.deviceId" style="width: 100%">
<!--              <el-input v-model="form.ctEndTime" placeholder="请输入结束时间(HH:mm)" />-->
              <el-time-picker
                v-model="form.ctEndTime"
                style="width: 100%"
                format='HH:mm'
                value-format="HH:mm"
                :editable="false">
              </el-time-picker>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="断电时间" name="ddInfo" v-if="showCols.scanPoweron">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="自动断电时间" prop="ddTime" v-if="form.deviceId" style="width: 100%">
              <el-time-picker
                v-model="form.ddTime"
                style="width: 100%"
                format='HH:mm'
                value-format="HH:mm"
                :editable="false">
              </el-time-picker>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 取电二维码弹窗 -->
    <el-dialog :title="qrcodeTitle" :visible.sync="qrcodeOpen" width="500px" append-to-body>
      <img :src="qrcodeUrl" width="100%">
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="downloadQr">下 载</el-button>
        <el-button @click="close">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 上报设备 -->
    <el-dialog :title="reportDeviceTitle" :visible.sync="reportDeviceOpen" width="500px" append-to-body>
      <el-table ref="reportDeviceTable" v-loading="reportDeviceLoading" :data="fixDeviceList" @selection-change="handleSelectDevice">
        <el-table-column label="设为固定" align="center" prop="flag" type="selection" width="55" />
        <el-table-column label="设备MAC" align="center" prop="mac" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSaveDevice">确 定</el-button>
        <el-button @click="close">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDevice,
  getDevice,
  delDevice,
  addDevice,
  updateDevice,
  updateDeviceWifi,
  updateDeviceCttime,
  updateDeviceDdtime,
  changeDeviceCircuitSwitch,
  changeDeviceScanPoweron,
  changeDeviceLavePoweroff,
  getDeviceQrcode,
  reportFixDevice,
  listFixDevice,
  saveFixDevice
} from "@/api/device/device";
import {hasMobile} from "@/utils/ruoyi";

export default {
  name: "Device",
  dicts: ['device_status','device_purchase_type','device_circuit_switch','device_hotel_layout','device_scan_poweron','device_leave_poweroff'],
  data() {
    return {
      // 不同产品下动态列控制
      showCols: {
        circuitSwitch: false,
        scanPoweron: false,
        leavePoweroff: false,
        wifi: false,
        reportDevice: false
      },
      isMobile: false,
      // 选中选项卡的 name
      activeName: "basic",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      deviceList: [],
      // 固定设备表格数据
      fixDeviceList: [],
      deviceName: '',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 取电二维码弹出层标题
      qrcodeTitle: "",
      // 是否显示取电二维码弹出层
      qrcodeOpen: false,
      // 上报设备弹出层遮罩层
      reportDeviceLoading: true,
      // 上报设备弹出层标题
      reportDeviceTitle: "",
      // 是否显示上报设备弹出层
      reportDeviceOpen: false,
      // 选中设备MAC
      macs: [],
      // 取电二维码图片URL
      qrcodeUrl: "",
      // 取电二维码图片命名
      qrcodeUrlName: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: this.$route.query.productId ? this.$route.query.productId : null,
        hotelId: null,
        deviceName: null,
        deviceSecret: null,
        roomName: null,
        roomAddress: null,
        roomLayout: null,
        roomPowerCapacity: null,
        roomPowerPrice: null,
        ctBeginTime: null,
        ctEndTime: null,
        leavePoweroff: null,
        scanPoweron: null,
        circuitSwitch: null,
        wifiName: null,
        wifiPswd: null,
        purchaseType: null,
        purchaseDeadline: null,
        status: null,
        activeTime: null,
        lastOnlineTime: null
      },
      // 产品选项
      productOptions: [],
      // 店长选项
      hotelOptions: [],
      // 表单参数
      form: {
        ctBeginTime: '22:00',
        ctEndTime: '08:00',
        ddTime: '12:00'
      },
      // 表单校验
      rules: {
        productId: [
          { required: true, trigger: "blur", message: "请选择设备所属产品" }
        ],
      },
      timer: null
    };
  },
  created() {
    const productId = this.$route.query.productId;
    if (productId !== undefined && productId !== '') {
      this.queryParams.productId = productId;
    }
    this.getList();
    if (hasMobile()) {
      this.isMobile = true;
      this.showSearch = false;
    }
    this.applyProductColumns();
  },
  activated(){
    const productId = this.$route.query.productId;
    if (productId !== undefined && productId !== '') {
      this.queryParams.productId = productId;
    }
    this.getList();
    if (hasMobile()) {
      this.isMobile = true;
      this.showSearch = false;
    }
    this.applyProductColumns();
  },
  methods: {
    // 根据所属产品控制列可见性
    applyProductColumns(){
      const pid = this.queryParams.productId;
      // 默认全部隐藏
      this.showCols = { circuitSwitch: false, scanPoweron: false, leavePoweroff: false, wifi: false, reportDevice: false };
      // 产品：XF8BMDHHB1（智能照明/控电类）
      if (pid === 'XF8BMDHHB1') {
        this.showCols.circuitSwitch = true;
        this.showCols.scanPoweron = true;
        this.showCols.leavePoweroff = true;
        this.showCols.wifi = true;
        this.showCols.reportDevice = true;
      }
      // 可在此添加更多产品的列配置
      // else if (pid === 'XXXXXXX') { ... }
    },
    /** 查询设备列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        this.productOptions = response.products;
        this.hotelOptions = response.hotels;
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 下载按钮
    downloadQr() {
      console.log("downloadQr?")
      this.downloadByBlob(this.qrcodeUrl, this.qrcodeUrlName);
    },
    downloadByBlob(url,name) {
      let image = new Image()
      image.setAttribute('crossOrigin', 'anonymous')
      image.src = url
      image.onload = () => {
        let canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        let ctx = canvas.getContext('2d')
        ctx.drawImage(image, 0, 0, image.width, image.height)
        canvas.toBlob((blob) => {
          let url = URL.createObjectURL(blob)

          let eleLink = document.createElement('a')
          eleLink.download = name
          eleLink.href = url
          eleLink.click()
          eleLink.remove()

          // 用完释放URL对象
          URL.revokeObjectURL(url)
        })
      }
    },
    // 关闭按钮
    close() {
      this.qrcodeOpen = false;
      this.reportDeviceOpen = false;

      if (this.timer) {
        clearInterval(this.timer);
      }
    },
    // 表单重置
    reset() {
      this.form = {
        deviceId: null,
        productId: null,
        hotelId: null,
        deviceName: null,
        deviceSecret: null,
        roomName: null,
        roomAddress: null,
        roomLayout: null,
        roomPowerCapacity: null,
        roomPowerPrice: null,
        ctBeginTime: '22:00',
        ctEndTime: '08:00',
        ddTime: '12:00',
        leavePoweroff: null,
        scanPoweron: null,
        circuitSwitch: null,
        wifiName: null,
        wifiPswd: null,
        purchaseType: null,
        purchaseDeadline: null,
        deviceCount: 1,
        status: "0",
        createBy: null,
        createTime: null,
        activeTime: null,
        lastOnlineTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.applyProductColumns();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const deviceId = row.deviceId || this.ids
      getDevice(deviceId).then(response => {
        this.form = response.data;
        this.productOptions = response.products;
        this.open = true;
        this.title = "修改设备";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deviceId != null) {
            if (this.activeName == "basic") {
              updateDevice(this.form).then(response => {
                if (response.code == 200) {
                  this.$modal.msgSuccess("修改成功");
                } else {
                  this.$modal.msgError(response.msg);
                  this.open = false;
                  this.getList();
                }
              });
            } else if (this.activeName == "wifiInfo") {
              updateDeviceWifi(this.form).then(response => {
                if (response.code == 200) {
                  this.$modal.msgSuccess("修改成功");
                } else {
                  this.$modal.msgError(response.msg);
                  this.open = false;
                  this.getList();
                }
              });
            } else if (this.activeName == "ctInfo") {
              updateDeviceCttime(this.form).then(response => {
                if (response.code == 200) {
                  this.$modal.msgSuccess("修改成功");
                } else {
                  this.$modal.msgError(response.msg);
                  this.open = false;
                  this.getList();
                }
              });
            } else if (this.activeName == "ddInfo") {
              updateDeviceDdtime(this.form).then(response => {
                if (response.code == 200) {
                  this.$modal.msgSuccess("修改成功");
                } else {
                  this.$modal.msgError(response.msg);
                  this.open = false;
                  this.getList();
                }
              });
            }
          } else {
            addDevice(this.form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess("新增成功");
              } else {
                this.$modal.msgError(response.msg);
              }
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 电路开关修改
    handleCircuitSwitchChange(row, circuitSwitch) {
      let oldCircuitSwitch = row.circuitSwitch;
      let text = circuitSwitch === "01" ? "远程断电" : "远程通电";
      if (circuitSwitch === "02") {
        text = "强制断电";
      }
      console.log(JSON.stringify(row));
      this.$modal.confirm('确定下发【' + text + '】指令吗？').then(function() {
        return changeDeviceCircuitSwitch(row.productId, row.deviceId, row.deviceName, circuitSwitch);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
        row.circuitSwitch = circuitSwitch;
      }).catch(function() {
        row.circuitSwitch = oldCircuitSwitch;
      });
    },
    // 取电二维码
    handleGetPowerQrcode(row) {
      getDeviceQrcode({ "deviceName": row.deviceName }).then(response => {
        if (response.code == 200) {
          this.qrcodeUrl = response.qrcodeUrl;
          this.qrcodeUrlName = "取电二维码_" + row.deviceName;
          this.qrcodeOpen = true;
          this.qrcodeTitle = "取电二维码";
        }
      });
    },
    // 上报固定设备
    handleReportDevice(row) {
      reportFixDevice({ "deviceName": row.deviceName }).then(response => {
        if (response.code == 200) {
          this.deviceName = row.deviceName;
          this.reportDeviceOpen = true;
          this.reportDeviceTitle = "设置固定设备";
          this.reportDeviceLoading = true;
          this.fixDeviceList = [];

          let _this = this;
          _this.timer = setInterval(function () {
            listFixDevice({ "deviceName": row.deviceName }).then(res => {
              console.log("res: "+JSON.stringify(res))
              if (res.total > 0) {
                _this.reportDeviceLoading = false;
                _this.fixDeviceList = res.rows;
                clearInterval(_this.timer);

                _this.$nextTick(()=>{
                  _this.fixDeviceList.forEach(device => {
                    if(device.flag == "1"){
                      console.log("设备mac："+device.mac+"为固定设备")
                      console.log(_this.$refs.reportDeviceTable);
                      _this.$refs.reportDeviceTable.toggleRowSelection(device,true);
                    }
                  })
                })
              }
            });
          }, 3000)
        }
      });
    },
    // 多选框选中固定设备
    handleSelectDevice(selection) {
      this.macs = selection.map(item => item.mac)
    },
    // 保存固定设备
    handleSaveDevice() {
      let _this = this;
      this.$modal.confirm('是否确认将所选设备设置为固定设备？').then(function() {
        console.log("deviceName="+_this.deviceName+", macs="+_this.macs)
        return saveFixDevice(_this.deviceName, _this.macs);
      }).then(() => {
        this.$modal.msgSuccess("设置固定设备成功");
        this.reportDeviceOpen = false;
      }).catch(() => {});
    },
    // 扫码开电修改
    handleScanPoweronChange(row) {
      let text = row.scanPoweron === "0" ? "禁用" : "启用";
      this.$modal.confirm('确认要' + text + '房间【' + row.roomName + '】的扫码开电状态吗？').then(function() {
        return changeDeviceScanPoweron(row.productId, row.deviceId, row.deviceName, row.scanPoweron);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.scanPoweron = row.scanPoweron === "0" ? "1" : "0";
      });
    },
    // 人走断电修改
    handleLeavePoweroffChange(row) {
      let text = row.leavePoweroff === "0" ? "关闭" : "开启";
      this.$modal.confirm('确认要' + text + '房间【' + row.roomName + '】的人走断电状态吗？').then(function() {
        return changeDeviceLavePoweroff(row.productId, row.deviceId, row.deviceName, row.leavePoweroff);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.leavePoweroff = row.leavePoweroff === "0" ? "1" : "0";
      });
    },
    /** 日志按钮操作 */
    handleLog(row) {
      const deviceName = row.deviceName;
      this.$router.push({ path: '/device/deviceLog', query: { deviceName: deviceName } })
    },
    /** 用电按钮操作 */
    handlePower(row) {
      const deviceName = row.deviceName;
      this.$router.push({ path: '/device/power', query: { deviceName: deviceName } })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId || this.ids;
      this.$modal.confirm('确认要删除编号为"' + deviceIds + '"的设备吗？').then(function() {
        return delDevice(deviceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('device/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style>
.el-message-box__btns {
  text-align: center !important;
}
</style>
